package com.szxy.forkjoin;

import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @Author:zwer
 * @Date:2020/5/24 20:37
 * @Description:com.szxy.forkjoin
 * @Version:1.0
 **/
public class ForkJoinCalCulationTest {

    private static final long total = 50000000000L;

    /**
     *  使用 Fork/Join 框架测试
     */
    @Test
    public void test01() {
        Instant start = Instant.now();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculation(0L, total);
        Long result = pool.invoke(task);
        System.out.println("result = " + result);

        Instant end = Instant.now();
        //  1000000000L 501 ms
        //  5000000000L 1907 ms
        System.out.println("耗时时间为：" + Duration.between(start, end).toMillis());

    }

    /**
     *  普通 for 循环
     */
    @Test
    public void test02() {
        Instant start = Instant.now();

        long sum  = 0L;
        for (long i = 0; i < total; i++) {
            sum += i;
        }
        System.out.println("sum = " + sum);

        Instant end = Instant.now();
        // 1000000000L  722 ms
        // 5000000000L  3045 ms
        System.out.println("耗时时间 = "+ Duration.between(start, end).toMillis());
    }

    /**
     * 并行流 parallel
     */
    @Test
    public void test03() {
        Instant start = Instant.now();
        long result = LongStream.rangeClosed(0L, total)
                .parallel()
                .reduce(Long::sum)
                .getAsLong();
        System.out.println("result = " + result);
        Instant end = Instant.now();
        System.out.println("耗时时间 = "+ Duration.between(start, end).toMillis());
    }
}
